package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Answer;
import cn.wolfcode.trip.base.domain.CommunityComment;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.AnswerMapper;
import cn.wolfcode.trip.base.mapper.CommunityCommentMapper;
import cn.wolfcode.trip.base.mapper.UserMapper;
import cn.wolfcode.trip.base.service.IAnswerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class AnswerServiceImpl implements IAnswerService {
    @Autowired
    private AnswerMapper answerMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CommunityCommentMapper commentMapper;

    @Override
    public void saveOrUpdate(Answer answer) {
        if (answer.getId() == null) {
            //回答时间
            Date date = new Date();
            answer.setAnswerTime(date);
            answerMapper.insert(answer);
        } else {
            answerMapper.updateByPrimaryKey(answer);
        }
    }


    @Override
    public List<Answer> queryAnswerContent(Long questionId) {
        //获取所有回答
        List<Answer> answers = answerMapper.selectAnswerContent(questionId);
        for (int i = 0; i < answers.size(); i++) {
            //获取单个回答
            Answer answer = answers.get(i);
            //获取所有评论
            List<CommunityComment> comments = answer.getComments();
            for (int j = 0; j < comments.size(); j++) {
                //获取单个评论
                CommunityComment comment = comments.get(j);
                //根据user的id 查询出user
                User user = userMapper.selectByPrimaryKey(comment.getUserId());
                //设置到评论
                comment.setUser(user);
            }
            //将评论设置到回答对象
            answer.setComments(comments);
        }
        //返回整个回答对象
        return answers;
    }

}
